package com.example.redisdemo.FilterToken;

import com.alibaba.fastjson.JSONObject;
import com.example.redisdemo.util.Result;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 *  Author  yangjiawna
 */

@WebFilter(value = {"/view/*"})
public class FilterToken implements Filter {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //Filter过滤器跨域处理
        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        //从请求头拿到Token
        String token = request.getHeader("token");
        //防止出现null报错
        token=token==null?"":token;
        //拿到剩余时间
        Long expire = redisTemplate.getExpire(token);
        if (expire>0){
                //设置成30分钟
            redisTemplate.expire("token",30L, TimeUnit.MINUTES);
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }
        //未登录，响应数据
        String string = JSONObject.toJSONString(new Result(103, "未登录", null));
         request.setAttribute("result",string);
        RequestDispatcher  requestDispatcher =request.getRequestDispatcher("./login");
         requestDispatcher.forward(request, response);

    }
}
